<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<%@ page import="java.sql.*" %>
<%@ page import="bean.DB" %>
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>用户列表</title>
    <style>
        table {
            border-collapse: collapse;
            width: 80%;
            margin: 20px auto;
        }
        th, td {
            border: 1px solid #ddd;
            padding: 8px;
            text-align: center;
        }
        th {
            background-color: #4CAF50;
            color: white;
        }
        tr:nth-child(even) {
            background-color: #f2f2f2;
        }
        tr:hover {
            background-color: #ddd;
        }
        .action-form {
            display: inline; /* 防止表单换行 */
        }
    </style>
</head>
<body>
<h1 style="text-align: center;">用户列表</h1>
<table>
    <thead>
    <tr>
        <th>ID</th>
        <th>用户名</th>
        <th>密码</th>
        <th>户籍</th>
        <th>性别</th>
        <th>生日</th>
        <th>地址</th>
        <th>删除</th>
        <th>修改</th>
    </tr>
    </thead>
    <tbody>
    <%
        DB db = new DB(); // 创建 DB 实例
        String sql = "SELECT id, username, password, origin, gender, birthday, address FROM users"; // 查询语句
        Connection conn = null;
        Statement stmt = null;
        ResultSet rs = null;

        try {
            conn = db.createConn(); // 获取连接
            stmt = conn.createStatement(); // 创建 Statement
            rs = stmt.executeQuery(sql); // 执行查询

            // 遍历 ResultSet 并生成表格行
            while (rs.next()) {
                int id = rs.getInt("id");
                String username = rs.getString("username");
                String password = rs.getString("password");
                String origin = rs.getString("origin");
                String gender = rs.getString("gender");
                String birthday = rs.getString("birthday");
                String address = rs.getString("address");
    %>
    <tr>
        <td><%= id %></td>
        <td><%= username %></td>
        <td><%= password %></td>
        <td><%= origin %></td>
        <td><%= gender %></td>
        <td><%= birthday %></td>
        <td><%= address %></td>
        <!-- 删除按钮 -->
        <td>
            <form class="action-form" action="./deleteUserServlet" method="post">
                <input type="hidden" name="id" value="<%= id %>">
                <button type="submit">删除</button>
            </form>
        </td>
        <!-- 修改按钮 -->
        <td>
            <button type="button" onclick="window.location.href='alterUser.jsp?id=<%= id %>'">修改</button>
        </td>
    </tr>
    <%
            }
        } catch (Exception e) {
            System.out.println("<tr><td colspan='9' style='color:red; text-align:center;'>加载数据失败：" + e.getMessage() + "</td></tr>");
        } finally {
            db.close(); // 确保资源释放
        }
    %>
    </tbody>
</table>
</body>
</html>
